package com.thinkbig.segment.tokenize;

import java.util.ArrayList;
import java.util.HashMap;

import com.thinkbig.segment.resource.Resourcer;


public class StatisticsMaxScore {
    private ArrayList<ArrayList<String>> result = null;
    private HashMap<Integer, HashMap<String, Double>> DICT = null;
    private String query = null;
    public boolean[][] map;

    public StatisticsMaxScore(String query) {
        assert (query != null && query.length() != 0);
        this.DICT = Resourcer.DICT;
        this.result = new ArrayList<ArrayList<String>>();
        int lenth = query.length();
        this.map = new boolean[lenth][lenth];
        for (int i = 0; i < lenth; i++) {
            for (int j = 0; j < lenth; j++) {
                map[i][j] = false;
            }
        }
        
        this.query = query;
    }
    
    public void generateMap() {
        for (int i = 0; i < query.length(); i++) {
            for (int j = i + 1; j <= query.length(); j++) {
                String q = query.substring(i, j);
                if (hasSegmentInDict(q)) {
                    map[i][j - 1] = true;
                }
            }
        }
    }

    public String tokenize() {
        for (int i = 0; i < query.length(); i++) {
            result = getResult(result, query.charAt(i));
        }
        return result.toString();
    }

    private ArrayList<ArrayList<String>> getResult(ArrayList<ArrayList<String>> father, char nextChar) {
        ArrayList<ArrayList<String>> rtn = new ArrayList<ArrayList<String>>();
        if (father.size() == 0) {
            ArrayList<String> list = new ArrayList<String>();
            list.add(String.valueOf(nextChar));
            rtn.add(list);
        } else {
            for (ArrayList<String> sub : father) {

                ArrayList<String> newSub = new ArrayList<String>();
                newSub.addAll(sub);
                newSub.add(String.valueOf(nextChar));
                rtn.add(newSub);

                int index = sub.size() - 1;
                String q = sub.get(index) + String.valueOf(nextChar);
                if (hasSegmentInDict(q)) {
                    sub.set(index, q);
                    rtn.add(sub);
                }
            }
        }
        return rtn;
    }

    private boolean hasSegmentInDict(String q) {
        assert (q != null && q.length() != 0);
        int lenth = q.length();
        return (DICT.get(lenth) != null && DICT.get(lenth).get(q) != null);
    }
}
